package com.twu.biblioteca.view;

import com.twu.biblioteca.events.Event;
import com.twu.biblioteca.events.Listener;
import com.twu.biblioteca.model.menu.MenuFormatter;
import com.twu.biblioteca.model.menu.exceptions.InvalidMenuSelectionException;
import com.twu.biblioteca.presenter.MenuPresenter;
import com.twu.biblioteca.view.utils.Input;
import com.twu.biblioteca.view.utils.Output;

import java.util.InputMismatchException;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 08/08/2013
 * Time: 10:04
 * To change this template use File | Settings | File Templates.
 */
public class MenuView implements MenuPresenter.Display{

    private final Output outputStream;
    private final Input inputStream;

    private Event inputEvent = new Event();
    private int userSelection;

    public MenuView(Output outputStream, Input inputStream) {
        this.outputStream = outputStream;
        this.inputStream = inputStream;
    }

    @Override
    public void init(MenuFormatter menuFormatter){
        try {
            showMenu(menuFormatter);
            getUserInput();
        } catch (InvalidMenuSelectionException e) {
            warnInvalidInput();
        }
    }

    void showMenu(MenuFormatter menuFormatter) {
        prompt();
        outputStream.write(menuFormatter.toFormattedString());
    }

    void getUserInput() throws InvalidMenuSelectionException {
        try{
            userSelection = inputStream.readInt();
            inputEvent.fire();
        } catch (InputMismatchException e){
            throw new InvalidMenuSelectionException();
        }
    }

    @Override
    public int getUserSelection(){
        return userSelection;
    }

    @Override
    public void warnInvalidInput() {
        outputStream.write(Messages.WARNING);
    }

    void prompt(){
        outputStream.write(Messages.PROMPT);
    }

    @Override
    public void addEventListener(Listener listener) {
        inputEvent.addListener(listener);
    }

    public enum Messages {
        PROMPT("Please select a valid option: "),
        WARNING("Select a valid option!!");

        private final String message;
        Messages(String message){ this.message = message; }
        public String toString() { return message; }
    }
}
